# -*-encoding=utf-8-*-

from django.http import HttpResponse, StreamingHttpResponse
from django.template import loader
from django.shortcuts import render_to_response, redirect, render, HttpResponseRedirect
from django.template import RequestContext
from django.template.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import PageNotAnInteger, Paginator, EmptyPage
from django.utils.encoding import escape_uri_path
from django.core.serializers.json import DjangoJSONEncoder
import datetime
from .models import Bug, BugUser, Project, Images, Demand, Mail, Files
from .form import AddBugForm, UserForm, AddDemandForm
from django.conf import settings
import os
import json


@csrf_exempt
def login(request):
    """
    登陆
    :param request:
    :return: bug_list
    """
    # 不允许重复登陆
    if request.method == 'POST':
        login_user = UserForm(request.POST)
        if login_user.is_valid():
            user_id = login_user.cleaned_data['username']
            password = login_user.cleaned_data['password']
            try:
                user = BugUser.objects.get(user_id__exact=user_id)
                if user.password == password:
                    response = redirect('/index/')
                    response.set_cookie('username', user_id)
                    return response
                else:
                    message = '密码不正确'
            except:
                message = '用户名不存在'
        return render(request, 'bugs/login.html', locals())
    login_form = UserForm()
    return render(request, 'bugs/login.html', locals())


def logout(request):
    if not request.COOKIES.get('is_login', None):
        return render(request, 'bugs/login.html', {})
    request.COOKIES.flush()
    return redirect('/login/')


def index(request):
    """
    主页：
        bug_list: user 能看到自己team 下的团队的bug数据；admin与engineer 可看到所有团队的数据
        demand_list:权限同上
    :param request:
    :return: bug
    """
    limit = 5
    if request.COOKIES.get('username'):
        # 获取登录中文名
        username = request.COOKIES.get('username')
        login_user = BugUser.objects.get(user_id=username)
        team = BugUser.objects.get(user_id=username).team
        # 权限
        authority = BugUser.objects.get(user_id=username).authority
        if authority == 'admin' or 'engineer':
            bug_list = Bug.objects.all()
        else:
            # 显示登录用户下team 的bug
            project_name = Project.objects.filter(team=team)
            bug_list = Bug.objects.filter(project=project_name).order_by('modify_time')

        # 获取bug发起人的相关信息
        bugs_message = []
        for bugs in bug_list:
            # bug 数据
            bugs_temp = {}
            owner_id = bugs.owner
            assignee_id = bugs.assignee
            modify_bug_user_id = bugs.modify_bug_user
            # 发起者信息
            owner_message = BugUser.objects.filter(user_id=owner_id).values_list('c_name', 'phone', 'email')
            # 处理者信息
            assignee_message = BugUser.objects.filter(user_id=assignee_id).values_list('c_name', 'phone', 'email')
            # bug最后修改人
            modify_bug_user = BugUser.objects.filter(user_id=modify_bug_user_id).values_list('c_name', flat=True)

            # bug 数据获取
            bugs_temp['id'] = bugs.id
            bugs_temp['project'] = bugs.project

            # luke add : project type for ORT
            bugs_temp['project_type'] = bugs.project.type

            bugs_temp['team'] = team
            bugs_temp['version'] = bugs.version
            bugs_temp['state'] = bugs.state
            bugs_temp['severity'] = bugs.severity
            bugs_temp['level'] = bugs.level

            bugs_temp['difficult'] = bugs.difficult

            # 预计完成时间
            bugs_temp['estime'] = bugs.estime
            bugs_temp['description'] = bugs.description
            bugs_temp['modify_bug_user'] = modify_bug_user[0]
            bugs_temp['create_time'] = bugs.create_time
            bugs_temp['modify_time'] = bugs.modify_time
            # 完成时间
            bugs_temp['success_time'] = bugs.success_time

            if bugs.success_time:
                bugs_temp['days'] = bugs.success_time - bugs.create_time
            else:
                pass
            # owner的相关信息
            bugs_temp['owner_c_name'] = owner_message[0][0]
            bugs_temp['owner_phone'] = owner_message[0][1]
            bugs_temp['owner_email'] = owner_message[0][2]
            # assignee的相关信息
            bugs_temp['assignee_c_name'] = assignee_message[0][0]
            bugs_temp['assignee_phone'] = assignee_message[0][1]
            bugs_temp['assignee_email'] = assignee_message[0][2]
            bugs_message.append(bugs_temp)

        # 获取demand数据
        demand_list = Demand.objects.all().order_by('modify_time')
        demand_message = []
        for demand in demand_list:
            # demand 数据
            demand_temp = {}
            owner_id = demand.owner
            assignee_id = demand.assignee
            # modify_demand_user_id = demand.modify_bug_user
            # 发起者信息
            owner_message = BugUser.objects.filter(user_id=owner_id).values_list('c_name', 'phone', 'email')
            # 处理者信息
            assignee_message = BugUser.objects.filter(user_id=assignee_id).values_list('c_name', 'phone', 'email')
            # bug最后修改人
            # modify_bug_user = BugUser.objects.filter(user_id=modify_demand_user_id).values_list('c_name', flat=True)

            # bug 数据获取
            demand_temp['id'] = demand.id
            demand_temp['name'] = demand.name

            demand_temp['require_type'] = demand.require_type

            demand_temp['team'] = team
            demand_temp['state'] = demand.state
            demand_temp['level'] = demand.level
            demand_temp['difficult'] = demand.difficult

            # 预计完成时间
            demand_temp['estime'] = demand.estime
            demand_temp['description'] = demand.description
            # demand_temp['modify_bug_user'] = modify_bug_user[0]
            demand_temp['create_time'] = demand.create_time
            demand_temp['modify_time'] = demand.modify_time
            # 完成时间
            demand_temp['success_time'] = demand.success_time

            if demand.success_time:
                demand_temp['days'] = demand.success_time - demand.create_time
            else:
                pass
            # owner的相关信息
            demand_temp['owner_c_name'] = owner_message[0][0]
            demand_temp['owner_phone'] = owner_message[0][1]
            demand_temp['owner_email'] = owner_message[0][2]
            # assignee的相关信息
            demand_temp['assignee_c_name'] = assignee_message[0][0]
            demand_temp['assignee_phone'] = assignee_message[0][1]
            demand_temp['assignee_email'] = assignee_message[0][2]
            demand_message.append(demand_temp)

        # 分页，每页显示5个
        paginator = Paginator(bugs_message, limit)
        paginator_d = Paginator(demand_message, limit)
        page = request.GET.get('page')
        try:
            bugs_message = paginator.page(page)
            demand_message = paginator_d.page(page)
        except PageNotAnInteger:  # 如果页码不是整数，则显示第一页
            bugs_message = paginator.page(1)
            demand_message = paginator_d.page(1)
        except EmptyPage:  # 页码超出范围，则显示最后一页
            bugs_message = paginator.page(paginator.num_pages)
            demand_message = paginator_d.page(paginator_d.num_pages)

        template = loader.get_template('bugs/index.html')
        context = RequestContext(request, {
            'bug_list': bug_list,
            'login_user': login_user,
            'authority': authority,
            'bugs_message': bugs_message,
            'demand_message': demand_message,
        })
        return HttpResponse(template.render(context))
    return redirect('/login/')


@csrf_exempt
def detail_bug(request, id):
    """
    bug详情页面，根据权限的不同，进行展示
    :param request:
    :return:
    """
    if request.COOKIES.get('username'):
        username = request.COOKIES.get('username')
        user_data = BugUser.objects.all()
        # bug 信息
        bug = Bug.objects.filter(id__exact=id)
        assignee = bug.values('assignee')
        assignee_message = BugUser.objects.filter(user_id=assignee)
        images = Images.objects.filter(bug__exact=id)

        # 项目信息
        project_id = bug.values_list('project_id', flat=True)
        project_data = Project.objects.filter(id=project_id)

        # 权限判断
        auth = BugUser.objects.filter(user_id=username).values_list('authority', flat=True)
        if 'admin' in auth:
            authority = '0'
        elif 'engineer' in auth:
            authority = '1'
        else:
            authority = '2'
        # 开发者信息
        engineer_data = BugUser.objects.filter(authority='engineer')

        # 受理人信息
        assignee_id = bug.values('assignee')
        assignee_message = BugUser.objects.filter(user_id=assignee_id)

        # 发起人信息
        owner_id = bug.values('owner')
        owner_message = BugUser.objects.filter(user_id=owner_id)

        # images
        images = Images.objects.filter(bug_id=id)
        # 传到前台的值
        context = RequestContext(request, {
            'bug': bug,
            'project_data': project_data,
            'owner_message': owner_message,
            'assignee_message': assignee_message,
            'user_data': user_data,
            'engineer_data': engineer_data,
            'authority': authority,
            'images': images,
        })

        return render(request, 'bugs/detail_bug.html', locals())


@csrf_exempt
def update_bug(request):
    """
    修改bug: 用戶可于此追加内容；bug受理人可于此修改bug受理状态
    :param request:
    :return:
    """
    if request.method == 'POST':
        user_id = request.COOKIES.get('username')
        bug_id = request.POST.get('id')
        # luke added
        pro_data = request.POST.get('project')
        bug = Bug.objects.filter(id__exact=bug_id)
        # 权限判断
        auth = BugUser.objects.filter(user_id=user_id).values_list('authority', flat=True)
        modify_bug_user = request.COOKIES.get('username')
        state = request.POST['state']
        # 状态完成时，获取完成时间(取当前时间)
        if state == '已完成':
            success_time = datetime.datetime.now()
            bug.update(success_time=success_time)

            # 当bug 已完成 时 存一条信息到Mail中
            mail = Mail(recipient=BugUser.objects.get(user_id__exact=bug[0].owner).email, project=pro_data,
                        message='fixed bug', bug_id=bug_id)
            mail.save()
        if auth[0] == 'engineer' or 'admin':
            if bug[0].estime is None:
                estime = request.POST['estime'].strip()
            else:
                estime = bug[0].estime
            difficult = request.POST['difficult']
            assignee = request.POST['assignee']
            bug.update(
                state=state,
                difficult=difficult,
                estime=estime,
                assignee=assignee,
                modify_bug_user=modify_bug_user,
            )

        elif auth[0] == 'admin':
            level = request.POST['level']
            bug.update(
                level=level,
            )
        elif auth[0] == 'user':
            bug.update(
                state=state,
                modify_bug_user=modify_bug_user,
            )
        # 修改时 可以继续上传图片
        img_files = request.FILES.getlist("image")
        # print(img_files)
        for img in img_files:
            pic = Images(image=img, bug=bug[0])
            pic.save()

        return redirect('bugs:index')
    else:
        context = {}
    return render(request, 'bugs/detail.html', locals())


def new_bug(request):
    """
    新增bug.
    :param request:
    :return:
    """
    # 获取该用户名下的团队的专案
    username = request.COOKIES.get('username')
    team = BugUser.objects.get(user_id=username).team
    project_data = Project.objects.filter(team=team)
    p_data = project_data.values()
    # version_data = Version.objects.filter(project=project_data)
    # 从form中获取前端数据
    form = AddBugForm()

    if request.POST:
        bugform = AddBugForm(request.POST)
        bugs_data = Bug.objects.all().order_by("-id")
        print('bugform:', bugform)
        # 验证数据
        if bugform.is_valid():
            print('new_bug1')
            bug_form = bugform.save(commit=False)
            # 获取项目的类型type
            pro_data = request.POST.get('project')
            pro_name = pro_data.split('--')[0]

            if pro_data.find('--') == -1:
                pro_type = None
                bug_form.project = Project.objects.get(name__exact=pro_name)
            else:
                pro_type = pro_data.split('--')[1]
                bug_form.project = Project.objects.get(name__exact=pro_name, type__exact=pro_type)
            # 存储bug_form
            bug_form.owner = request.COOKIES.get('username')
            bug_form.modify_bug_user = request.COOKIES.get('username')
            bug_form.save()

            # 获取最新保存的bug（bug_form）
            bugs_data = Bug.objects.all().order_by("-id")

            # 图片信息
            img_files = request.FILES.getlist("image")
            for img in img_files:
                pic = Images(bug=bugs_data[0], image=img)
                pic.save()
            print('save success....')
            # 当增加一个bug时 存一条信息到Mail中
            mail = Mail(recipient=BugUser.objects.get(user_id__exact=bug_form.assignee).email, project=pro_data,
                        message='new bug', bug_id=bugs_data[0].id)
            mail.save()
            return redirect('/index/')

    context = {
        'form': form,
        'project_data': project_data,
        'p_data': p_data
    }
    context.update(csrf(request))
    return render_to_response('bugs/new_bug.html', context)


def new_demand(request):
    """
    新增需求：用户可通过此处新增新的项目需求
    :param request:
    :return:
    """
    demand_form = AddDemandForm()
    if request.POST:
        demand_form = AddDemandForm(request.POST, request.FILES)
        files_data = request.FILES.getlist('file')
        # print('files_data', files_data)
        # 验证表单数据
        if demand_form.is_valid():
            demand_form = demand_form.save(commit=False)
            # 需求提交者
            demand_form.owner = request.COOKIES.get('username')
            # 预定开会时间
            demand_form.meeting_time = request.POST['meeting_time']
            demand_form.save()
            # 获取最新的 demand (demand_form), 遍历上传的文件并保存
            newest_demand = Demand.objects.all().order_by('-create_time')[0]
            for _file in files_data:
                f = Files(file=_file, demand=newest_demand, name=_file.name)
                f.save()

            return redirect('/index/')
    context = {
        'form': demand_form,
    }
    context.update(csrf(request))
    return render(request, 'bugs/new_demand.html', context)


def detail_demand(request, id):
    print('demail_demand')
    if request.COOKIES.get('username'):
        username = request.COOKIES.get('username')
        user_data = BugUser.objects.all()
        # demand 信息
        demand_data = Demand.objects.filter(id__exact=id)
        print('demand_data:', demand_data)
        assignee = demand_data.values('assignee')
        assignee_message = BugUser.objects.filter(user_id=assignee)
        # images = Images.objects.filter(bug__exact=id)

        # 项目信息
        # project_id = bug.values_list('project_id', flat=True)
        # project_data = Project.objects.filter(id=project_id)

        # 权限判断
        auth = BugUser.objects.filter(user_id=username).values_list('authority', flat=True)
        if 'admin' in auth:
            authority = '0'
        elif 'engineer' in auth:
            authority = '1'
        else:
            authority = '2'
        # 开发者信息
        engineer_data = BugUser.objects.filter(authority='engineer')

        # 受理人信息
        assignee_id = demand_data.values('assignee')
        assignee_message = BugUser.objects.filter(user_id=assignee_id)

        # 发起人信息
        owner_id = demand_data.values('owner')
        owner_message = BugUser.objects.filter(user_id=owner_id)

        # files
        files = Files.objects.filter(demand_id=id)
        # print('demand_data1:', demand_data.values())
        # 传到前台的值
        context = {
            'demand_data': demand_data,
            # 'project_data': project_data,
            'owner_message': owner_message,
            'assignee_message': assignee_message,
            'user_data': user_data,
            'engineer_data': engineer_data,
            'authority': authority,
            'files': files,
        }
        return render(request, 'bugs/detail_demand.html', locals())


@csrf_exempt
def project(request):
    """
    project:用户管理界面
    :param request:
    :return: 现有project数据
    """
    print('project')
    limit = 6
    # project 数据
    project_data = Project.objects.all().order_by('team')
    if request.is_ajax:
        # project 管理：增 删 改
        # 删
        if request.POST.get('action') == 'delete':
            print('delete')
            active_id = request.POST.get('active_id')
            Project.objects.filter(id__exact=active_id).delete()
            return HttpResponse(json.dumps('delete'))
        # 增
        if request.POST.get('action') == 'add':
            print('add')
            print(request.POST.get('form_data'))
            form_data = split_data(request.POST.get('form_data'))
            print('form_data:', form_data)
            name = form_data.get('name')
            path = form_data.get('path')
            team = form_data.get('team')
            type = form_data.get('type')
            DRI = form_data.get('DRI')
            print('1:', name, path, team, type, DRI)
            Project.objects.create(
                name=name, path=path, team=team, type=type, DRI=DRI
            )
            return HttpResponse(json.dumps('add'))
        # 修改
        if request.POST.get('action') == 'select':
            active_id = request.POST.get('active_id')
            print('select', active_id)
            data = list(Project.objects.filter(id__exact=active_id).values())
            return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder))

        if request.POST.get('action') == 'update':
            print('update aaaa')
            form_data = split_data(request.POST.get('form_data'))

            Project.objects.filter(id__exact=form_data.get('pro_id')).update(
                name=form_data.get('name'),
                path=form_data.get('path'),
                team=form_data.get('team'),
                type=form_data.get('type'),
                DRI=form_data.get('DRI'),
            )
            return HttpResponse(json.dumps('update'))

    # 分页，每页显示9个
    paginator = Paginator(project_data, limit)
    page = request.GET.get('page')
    try:
        project_data = paginator.page(page)
    except PageNotAnInteger:  # 如果页码不是整数，则显示第一页
        project_data = paginator.page(1)
    except EmptyPage:  # 页码超出范围，则显示最后一页
        project_data = paginator.page(paginator.num_pages)
    context = {
        'project_data': project_data,
    }
    return render(request, 'bugs/project.html', context)


def split_data(data):
    """
    处理前台传进来的参数
    :param para:
    :return:list
    """
    list = []
    # 将字符串的 '=' 替换成 '：'
    # data1 = data.replace('=', ':')
    # 用‘&’将字符串分开
    data_list = data.split('&')
    form_dict = {}
    for dict_str in data_list:
        dict_str = dict_str.strip()
        key_val = dict_str.split("=")
        form_dict[key_val[0]] = key_val[-1]

    return form_dict


@csrf_exempt
def add_user(request):
    """
    用户管理：新增用户
    :param request:
    :return:
    """
    if request.method == 'POST':
        # 获取前端传过来的数据
        userid = request.POST['userid']
        user_data = BugUser.objects.all()
        if userid in user_data.values_list('user_id', flat=True):
            message = '该用户已存在！重新输入'
        else:
            # 获取页面的值
            c_name = request.POST['c_name']
            e_name = request.POST['e_name']
            password = request.POST['password']
            authority = request.POST['authority']
            phone = request.POST['phone']
            team = request.POST['team']
            # 将传进来的值赋值给buguser
            BugUser.objects.create(
                user_id=userid,
                c_name=c_name,
                e_name=e_name,
                password=password,
                authority=authority,
                phone=phone,
                team=team
            )
            return HttpResponseRedirect('/index/')
    return render(request, 'bugs/add_user.html', locals())


@csrf_exempt
def search_user(request):
    """
    用户管理：查找用户
    :param request:
    :return:
    """
    if request.method == 'POST':
        userid = request.POST.get('userid')
        user_data = BugUser.objects.filter(user_id=userid)
        context = {
            'user_data': user_data,
        }
        return render(request, 'bugs/search_user.html', context)


@csrf_exempt
def update_user(request):
    """
    用户管理：修改用户
    :param request:
    :return:
    """
    if request.method == 'POST':
        userid = request.POST.get('userid')
        user_data = BugUser.objects.filter(user_id=userid)
        password = request.POST['password']
        authority = request.POST['authority']
        phone = request.POST['phone']
        team = request.POST['team']
        # 修改
        user_data.update(
            password=password,
            authority=authority,
            phone=phone,
            team=team
        )
        return redirect('/index/')
    else:
        return render(request, 'bugs/update_user.html')


@csrf_exempt
def delete_user(request):
    if request.user and request.user.is_authenticated:
        return render(request, 'bugs/delete_user.html', {})


# 删除(操作)
@csrf_exempt
def delete_form(request):
    if request.method == 'POST':
        userid = request.POST.get('userid')
        user_data = BugUser.objects.filter(user_id=userid)
        return render_to_response('bugs/delete_user.html', {'user_data': user_data})
    else:
        return render_to_response('bugs/delete_user.html', {'fail': True})


@csrf_exempt
def delete_form_confirm(request):
    if request.method == 'POST':
        userid = request.POST.get('userid')
        user_data = BugUser.objects.filter(user_id=userid)
        user_data.delete()
        return redirect('/index/')
    else:
        return render(request, 'bugs/index.html')


def download_file(request, id):
    if request:
        # print('root:', settings.MEDIA_ROOT, os.pathsep)
        # print('request:',id)
        thisFile = Files.objects.get(id__exact=id)
        filePath = settings.MEDIA_ROOT + '//' + str(thisFile.file)
        fileName = thisFile.name

        def file_iterator(file_name, chunk_size=512):
            # print('file_name:', file_name)
            with open(file_name, 'rb') as f:
                while True:
                    c = f.read(chunk_size)
                    if c:
                        yield c
                    else:
                        break

        # if os.path.exists (filePath):
        response = StreamingHttpResponse(file_iterator(filePath))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(fileName))
        return response
